package com.elitel.frame.base.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.elitel.frame.base.service.BaseQueryfieldService;
import com.elitel.frame.base.service.BaseRepdatasourceService;
import com.elitel.frame.base.service.BaseRepparmeterService;
import com.elitel.frame.base.service.BaseReptempletService;
import com.elitel.frame.base.service.CfgExtreportService;
import com.elitel.frame.core.util.FileControlUtil;
import com.elitel.frame.main.entity.BaseQueryfield;
import com.elitel.frame.main.entity.BaseRepdatasource;
import com.elitel.frame.main.entity.BaseRepparmeter;
import com.elitel.frame.main.entity.BaseReptemplate;
import com.elitel.frame.main.entity.CfgExtreport;
import com.elitel.frame.main.entity.ext.CfgExtreportExt;
import com.elitel.frame.main.entity.vo.JsonResult;

/**
 * @author Fan
 * @ClassName: ReportServerController
 * @Description: TODO(报表服务)
 * @date 2018年1月5日
 */
@Controller
@RequestMapping("/system/reportconfig")
public class CfgExtReportServerController {
    private static final Logger logger = LoggerFactory.getLogger(CfgExtReportServerController.class);

    @Autowired
    private CfgExtreportService cfgExtreportService;
    @Autowired
    private BaseReptempletService baseReptempletService;
    @Autowired
    private BaseRepparmeterService baseRepparmeterService;
    @Autowired
    private BaseRepdatasourceService baseRepdatasourceService;
    @Autowired
    private HttpServletRequest httpServletRequest;
    @Autowired
    private BaseQueryfieldService baseQueryfieldService;


    /**
     * @param @param  guid
     * @param @return
     * @return Object
     * @Title: getReportServerByGuid
     * @Description: TODO(根据主键获取报表服务配置信息)
     */
    @RequestMapping("/getReportConfigByGuid")
    @ResponseBody
    public Object getReportConfigByGuid(String guid) {
        JsonResult jr = new JsonResult();
        try {
            CfgExtreport cfgExtreport = cfgExtreportService.getReportConfigByGuid(guid);
            jr.setData(cfgExtreport);
            jr.setSuccess(true);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            jr.setMsg("获取报表服务异常！");
            jr.setSuccess(false);
        }
        return jr;
    }


    @RequestMapping("/getReportConfigInformationByGuid")
    @ResponseBody
    public Object getReportConfigInformationByGuid(String guid) {
        JsonResult jr = new JsonResult();
        try {
            CfgExtreportExt cfgExtreport = cfgExtreportService.getReportConfigInformationByGuid(guid);
            jr.setData(cfgExtreport);
            jr.setSuccess(true);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            jr.setMsg("获取报表服务异常！");
            jr.setSuccess(false);
        }
        return jr;
    }

    /**
     * <pre>uploadReportTemplate(上传报表模板到session)
     * @author：FanWenquan
     * @date：2018年2月7日 上午10:08:45
     * @param myFile
     * @param request
     * @param response
     * @return</pre>
     */
    @RequestMapping("/uploadReportTemplate")
    public @ResponseBody
    Object uploadReportTemplate(@RequestParam("file") MultipartFile file,
                                HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        if (file != null) {
            //String uploadRootPath = request.getSession().getServletContext().getRealPath("/WEB-INF/jasper");
            String uploadRootPath = "main-frame-file/jasper";
            File uploadRootDir = new File(uploadRootPath);
            // Create directory if it not exists.
            if (!uploadRootDir.exists()) {
                uploadRootDir.mkdirs();
            }
            String lname = file.getOriginalFilename();
            try {
                byte[] bytes = file.getBytes();
                // Create the file on server
                File serverFile = new File(uploadRootDir.getAbsolutePath()
                        + File.separator + lname);

                BufferedOutputStream stream = new BufferedOutputStream(
                        new FileOutputStream(serverFile));
                stream.write(bytes);
                stream.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
            session.setAttribute("reportJasperUrl", "main-frame-file/jasper/" + lname);
            return true;
        } else {
            return false;
        }

    }

    /**
     * <pre>uploadReporrtJrxml(上传Jrxml进入Session)
     * @author：FanWenquan
     * @date：2018年2月7日 上午10:07:55
     * @param myFile
     * @param request
     * @param response
     * @return</pre>
     */
    @RequestMapping("/uploadReporrtJrxml")
    public @ResponseBody
    Object uploadReporrtJrxml(@RequestParam("file") MultipartFile file,
                              HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        if (file != null) {
            //String uploadRootPath = request.getSession().getServletContext().getRealPath("/WEB-INF/jasper");
            String uploadRootPath = "main-frame-file/jasper";
            File uploadRootDir = new File(uploadRootPath);
            // Create directory if it not exists.
            if (!uploadRootDir.exists()) {
                uploadRootDir.mkdirs();
            }
            String lname = file.getOriginalFilename();
            try {
                byte[] bytes = file.getBytes();
                // Create the file on server
                File serverFile = new File(uploadRootDir.getAbsolutePath()
                        + File.separator + lname);

                BufferedOutputStream stream = new BufferedOutputStream(
                        new FileOutputStream(serverFile));
                stream.write(bytes);
                stream.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
            session.setAttribute("reportJrxmlUrl", "main-frame-file/jasper/" + lname);
            return true;
        } else {
            return false;
        }
    }

    /**
     * <pre>uploadDataSourceFile(上传数据源文件)
     * @author：FanWenquan
     * @date：2018年2月8日 上午9:48:52
     * @param file
     * @param request
     * @param response
     * @return</pre>
     */
    @RequestMapping("/uploadDataSourceFile")
    public @ResponseBody
    Object uploadDataSourceFile(@RequestParam("file") MultipartFile file, String operate, String serviceId,
                                HttpServletRequest request, HttpServletResponse response) {
        Boolean bol = false;
        HttpSession session = request.getSession();
        JsonResult jr = new JsonResult();
        if (file != null) {
            List<BaseRepdatasource> list = dataServerfromtemplate(operate, serviceId);
            if (null != list) {
                SAXReader saxx = new SAXReader();
                Document documentedit;
                try {
                    documentedit = saxx.read(file.getInputStream());
                    Element editroot = documentedit.getRootElement();
                    String dbname = editroot.element("name").getTextTrim();
                    for (BaseRepdatasource baseRepdatasource : list) {
                        if (null != baseRepdatasource.getRemark() && dbname.equals(baseRepdatasource.getRemark())) {
                            bol = true;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (bol) {
                //String uploadRootPath = request.getSession().getServletContext().getRealPath("/WEB-INF/jasper/jsondata");
                String uploadRootPath = "main-frame-file/jasper/jsondata";
                File uploadRootDir = new File(uploadRootPath);
                // Create directory if it not exists.
                if (!uploadRootDir.exists()) {
                    uploadRootDir.mkdirs();
                }
                String lname = file.getOriginalFilename();
                try {
                    byte[] bytes = file.getBytes();
                    // Create the file on server
                    File serverFile = new File(uploadRootDir.getAbsolutePath()
                            + File.separator + lname);

                    BufferedOutputStream stream = new BufferedOutputStream(
                            new FileOutputStream(serverFile));
                    stream.write(bytes);
                    stream.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
                Set<String> set = new HashSet<String>();
                if (session.getAttribute("dataJsonXml") != null) {
                    set = (Set<String>) session.getAttribute("dataJsonXml");
                }
                set.add("main-frame-file/jasper/jsondata/" + lname);
                session.setAttribute("dataJsonXml", set);

                jr.setMsg("文件上传成功");
                jr.setSuccess(true);
            } else {
                jr.setMsg("文件无效,请重新上传！");
                jr.setSuccess(false);
            }
            return jr;
        } else {
            jr.setMsg("请选择文件进行上传！");
            jr.setSuccess(false);
            return jr;
        }
    }


    /**
     * <pre>getdataServerConfig(为报表数据源配置服务地址)
     * @author：FanWenquan
     * @date：2018年2月8日 下午3:29:25
     * @param operate
     * @param serviceId</pre>
     */
    public Boolean getdataServerConfig(String operate, String serviceId) {
        Boolean bol = false;
        HttpSession session = httpServletRequest.getSession();
        Set<String> set = (Set<String>) session.getAttribute("dataJsonXml");
        List<BaseRepdatasource> list = dataServerfromtemplate(operate, serviceId);
        try {
            if (set != null && set.size() > 0) {
                for (String str : set) {
                    //String filePath = httpServletRequest.getSession().getServletContext().getRealPath(str);
                    File xmlFile = new File(str);
                    SAXReader saxx = new SAXReader();
                    Document documentedit = saxx.read(xmlFile);
                    Element editroot = documentedit.getRootElement();
                    Element element = editroot.element("dataFile");
                    String url = element.element("url").getTextTrim();
                    String dbname = editroot.element("name").getTextTrim();
                    if (url.length() > 0) {
                        String afterbus = StringUtils.substringAfter(url, "/business/");
                        String servertype = StringUtils.substringBefore(afterbus, "/");
                        String servicecode = StringUtils.substringAfter(url, "serviceID=");
                        if (servicecode.contains("&")) {
                            servicecode = StringUtils.substringBefore(afterbus, "&");
                        }
                        for (BaseRepdatasource db : list) {
                            if (null != db.getRemark() && dbname.equals(db.getRemark())) {
                                switch (servertype) {
                                    case "singleServer"://单表
                                        db.setServicetype("singleTableServer");
                                        break;
                                    case "multipleServer"://脚本
                                        db.setServicetype("executeSqlServer");
                                        break;
                                    case "extMasterServer"://主从
                                        db.setServicetype("masterConfigServer");
                                        break;
                                }
                                db.setDataserviceid(servicecode);
                                db.setDatasourceurl(str);
                                break;
                            }
                        }
                    }
                }
            }
            session.setAttribute("reportDataServerList", list);
            bol = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bol;
    }

    /**
     * <pre>dataServerConfig(从模板文件获取数据源配置)
     * @author：FanWenquan
     * @date：2018年2月8日 下午2:52:37
     * @param operate
     * @param serviceId
     * @return</pre>
     */
    public List<BaseRepdatasource> dataServerfromtemplate(String operate, String serviceId) {
        List<BaseRepdatasource> list = new ArrayList<BaseRepdatasource>();
        HttpSession session = httpServletRequest.getSession();
        String jrxmlurl = "";
        if (null != session.getAttribute("reportJrxmlUrl")) {
            jrxmlurl = session.getAttribute("reportJrxmlUrl").toString();
        }
        //String filePath ="";
        try {
            if (null != jrxmlurl && !"".equals(jrxmlurl)) {
                //filePath = httpServletRequest.getSession().getServletContext().getRealPath(jrxmlurl);
                File xmlFile = new File(jrxmlurl);
                SAXReader saxx = new SAXReader();
                Document documentedit = saxx.read(xmlFile);
                Element editroot = documentedit.getRootElement();
                List<Element> parmeterlist = editroot.elements("parameter");
                for (Element element : parmeterlist) {
                    String classvalue = element.attributeValue("class");
                    int lastindexof = classvalue.lastIndexOf(".");
                    String type = classvalue.substring(lastindexof + 1);
                    if (null != type && type.equals("JRBeanCollectionDataSource")) {
                        BaseRepdatasource datasource = new BaseRepdatasource();
                        datasource.setGuid(UUID.randomUUID().toString());
                        datasource.setServicecode(serviceId);
                        datasource.setRepdatasource(element.attributeValue("name"));
                        datasource.setDatesourcedesc(element.elementText("parameterDescription"));
                        datasource.setIsdefault(1L);
                        Element summary = editroot.element("summary");
                        List<Element> datalist = getNodes(summary, "dataset");
                        for (Element dbset : datalist) {
                            String dbsourceEx = dbset.element("datasetRun").element("dataSourceExpression").getTextTrim();
                            if (null != dbsourceEx && dbsourceEx.contains(element.attributeValue("name"))) {
                                String attributeValue = dbset.element("datasetRun").attributeValue("subDataset");
                                List<Element> sublist = editroot.elements("subDataset");
                                for (Element sub : sublist) {
                                    if (sub.attributeValue("name").equals(attributeValue)) {
                                        List<Element> elements = sub.elements("property");
                                        for (Element prop : elements) {
                                            if ("com.jaspersoft.studio.data.defaultdataadapter".equals(prop.attributeValue("name"))) {
                                                datasource.setRemark(prop.attributeValue("value"));
                                                break;
                                            }
                                        }
                                        break;
                                    }
                                }
                                break;
                            }
                        }
                        list.add(datasource);
                    }
                }
                BaseRepdatasource defaultds = new BaseRepdatasource();
                defaultds.setGuid(UUID.randomUUID().toString());
                defaultds.setServicecode(serviceId);
                defaultds.setRepdatasource("DefaultDataSource");
                defaultds.setDatesourcedesc("默认数据源");
                defaultds.setIsdefault(0L);
                List<Element> properitylist = editroot.elements("property");
                for (Element element : properitylist) {
                    String pname = element.attributeValue("name");
                    if (pname.equals("com.jaspersoft.studio.data.defaultdataadapter")) {
                        defaultds.setRemark(element.attributeValue("value"));
                        break;
                    }
                }
                list.add(defaultds);
            } else if (jrxmlurl.equals("") && operate.equals("edit")) {
                BaseReptemplate reptemplate = baseReptempletService.getReptemplateByServiceid(serviceId);
                list = baseRepdatasourceService.getReportDataSourceByServer(serviceId);
            }
            session.setAttribute("reportDataServerList", list);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return list;
    }

    /**
     * <pre>saveServerId(保存报表服务id入session)
     * @author：FanWenquan
     * @date：2018年2月7日 上午10:07:27
     * @param reportserverID
     * @return</pre>
     */
    @RequestMapping("/saveServerId")
    @ResponseBody
    public Object saveServerId(String reportserverID) {
        HttpSession session = httpServletRequest.getSession();
        if (reportserverID != null && !"".equals(reportserverID)) {
            session.setAttribute("reportserverID", reportserverID);
            return true;
        } else {
            return false;
        }
    }

    /**
     * <pre>getReportDataSourceSize(获取数据源个数并将数据源配置添加到session缓存)
     * @author：FanWenquan
     * @date：2018年2月7日 上午11:02:27
     * @param operate
     * @param serviceId
     * @return</pre>
     */
    @SuppressWarnings("unused")
    @RequestMapping("/getReportDataSourceSize")
    @ResponseBody
    public Object getReportDataSourceSize(String operate, String serviceId) {
        int size = 0;
        JsonResult jr = new JsonResult();
        List<BaseRepdatasource> list = new ArrayList<BaseRepdatasource>();
        HttpSession session = httpServletRequest.getSession();
        String jrxmlurl = "";
        if (null != session.getAttribute("reportJrxmlUrl")) {
            jrxmlurl = session.getAttribute("reportJrxmlUrl").toString();
        }
        String filePath = "";
        try {
            if (null != jrxmlurl && !"".equals(jrxmlurl)) {
                filePath = jrxmlurl;//httpServletRequest.getSession().getServletContext().getRealPath(jrxmlurl);
            } else if (jrxmlurl.equals("") && operate.equals("edit")) {
                BaseReptemplate reptemplate = baseReptempletService.getReptemplateByServiceid(serviceId);
                //获取模板文件目录位置
//        		session.setAttribute("reportJasperUrl", reptemplate.getTemplateUrl());
//        		session.setAttribute("reportJrxmlUrl", reptemplate.getJrxmlUrl());
                filePath = reptemplate.getJrxmlUrl();//httpServletRequest.getSession().getServletContext().getRealPath(reptemplate.getJrxmlUrl());
            }
            if (!"".equals(filePath)) {
                File xmlFile = new File(filePath);
                SAXReader saxx = new SAXReader();
                Document documentedit = saxx.read(xmlFile);
                Element editroot = documentedit.getRootElement();
                List<Element> parmeterlist = editroot.elements("parameter");
                for (Element element : parmeterlist) {
                    String classvalue = element.attributeValue("class");
                    int lastindexof = classvalue.lastIndexOf(".");
                    String type = classvalue.substring(lastindexof + 1);
                    if (null != type && type.equals("JRBeanCollectionDataSource")) {
                        BaseRepdatasource datasource = new BaseRepdatasource();
                        datasource.setGuid(UUID.randomUUID().toString());
                        datasource.setServicecode(serviceId);
                        datasource.setRepdatasource(element.attributeValue("name"));
                        datasource.setDatesourcedesc(element.elementText("parameterDescription"));
                        datasource.setIsdefault(1L);
                        list.add(datasource);
                        size++;
                    }
                }
            }
            session.setAttribute("dataSourceInfoTemp", list);
            jr.setSuccess(true);
            jr.setData(list);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            jr.setSuccess(false);
        }
        return jr;
    }

    /**
     * <pre>getNodes(调用某节点下面的所有dataset节点)
     * @author：FanWenquan
     * @date：2018年2月7日 下午7:06:10
     * @param node
     * @return</pre>
     */
    private List<Element> getNodes(Element node, String elementname) {
        List<Element> list = new ArrayList<Element>();
        //递归遍历当前节点所有的子节点
        List<Element> listElement = node.elements();//所有一级子节点的list
        for (Element e : listElement) {//遍历所有一级子节点
            if (e.getName().equals(elementname)) {
                list.add(e);
            }
            List<Element> nodes = this.getNodes(e, elementname);//递归
            for (Element element : nodes) {
                list.add(element);
            }
        }
        return list;
    }

    /**
     * <pre>getReportParmeters(获取报表模板的参数列表)
     * @author：FanWenquan
     * @date：2018年2月7日 下午3:36:01
     * @param operate
     * @param serviceId
     * @return</pre>
     */
    @RequestMapping("/getReportParmeters")
    @ResponseBody
    public Object getReportParmeters(String operate, String serviceId) {
        JsonResult jr = new JsonResult();
        List<BaseRepparmeter> list = null;
        HttpSession session = httpServletRequest.getSession();
        String jrxmlurl = "";
        if (null != session.getAttribute("reportJrxmlUrl")) {
            jrxmlurl = session.getAttribute("reportJrxmlUrl").toString();
        }

        try {
            if (null != session.getAttribute("reportParmeterList")) {
                list = (List<BaseRepparmeter>) session.getAttribute("reportParmeterList");
            } else if (null != jrxmlurl && !"".equals(jrxmlurl)) {
                list = getParmeterBySession(jrxmlurl, serviceId);
            } else if (operate.equals("edit") && "".equals(jrxmlurl)) {
                list = baseRepparmeterService.getReportParmByServerByType(serviceId, "templateparmeter");
            }

            session.setAttribute("reportParmeterList", list);
            jr.setData(list);
            jr.setSuccess(true);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            jr.setSuccess(false);
            jr.setMsg("获取报表模板属性参数异常");
        }
        return jr;
    }

    /**
     * <pre>getParmeterBySession(根据xml文件获取)
     * @author：FanWenquan
     * @date：2018年2月7日 下午3:52:40
     * @param jrxmlurl
     * @return</pre>
     */
    private List<BaseRepparmeter> getParmeterBySession(String jrxmlurl, String serviceId) throws Exception {
        List<BaseRepparmeter> list = new ArrayList<BaseRepparmeter>();
        if (null != jrxmlurl && !"".equals(jrxmlurl)) {
            String filePath = jrxmlurl;//httpServletRequest.getSession().getServletContext().getRealPath(jrxmlurl);
            File xmlFile = new File(filePath);
            SAXReader sax = new SAXReader();
            Document document = sax.read(xmlFile);
            Element root = document.getRootElement();
            List<Element> parmeterlist = root.elements("parameter");
            for (Element element : parmeterlist) {
                String classvalue = element.attributeValue("class");
                int lastindexof = classvalue.lastIndexOf(".");
                String type = classvalue.substring(lastindexof + 1);
                if (null != type && !type.equals("JRBeanCollectionDataSource")) {
                    BaseRepparmeter repparmeter = new BaseRepparmeter();
                    repparmeter.setGuid(UUID.randomUUID().toString());
                    repparmeter.setParmetername(element.attributeValue("name"));
                    repparmeter.setAliasname(element.attributeValue("name"));
                    repparmeter.setDatatype(type);
                    repparmeter.setParmetertype("templateparmeter");
                    repparmeter.setParmeterdesc(element.elementText("parameterDescription"));
                    repparmeter.setServicecode(serviceId);
                    repparmeter.setIsterm("1");
                    list.add(repparmeter);
                }
            }
        }
        return list;
    }

    @RequestMapping("/getDateSourceServerConfig")
    @ResponseBody
    public Object getDateSourceServerConfig(String operate, String serviceId) {
        Boolean bool = getdataServerConfig(operate, serviceId);
        HttpSession session = httpServletRequest.getSession();
        List<BaseRepdatasource> dblist = new ArrayList<BaseRepdatasource>();
        if (null != session.getAttribute("reportDataServerList") && bool) {
            dblist = (List<BaseRepdatasource>) session.getAttribute("reportDataServerList");

        }
        return dblist;
    }

    /**
     * <pre>getDataServerParmeters(获取数据源参数条件)
     * @author：FanWenquan
     * @date：2018年2月8日 上午10:34:50
     * @param operate
     * @param serviceId
     * @return</pre>
     */
    @RequestMapping("/getDataServerParmeters")
    @ResponseBody
    public Object getDataServerParmeters(String operate, String serviceId, String dataserviceid) {
        Boolean bool = getdataServerConfig(operate, serviceId);
        JsonResult jr = new JsonResult();
        List<BaseRepparmeter> list = new ArrayList<BaseRepparmeter>();
        HttpSession session = httpServletRequest.getSession();
        Set<String> set = (Set<String>) session.getAttribute("dataJsonXml");
        if (null != session.getAttribute("dataServerParmeterList") && null == set) {
            list = (List<BaseRepparmeter>) session.getAttribute("dataServerParmeterList");
        } else if (null == set && operate.equals("edit")) {
            list = baseRepparmeterService.getReportParmByServerByType(serviceId, "dataserverparmeter");
        } else if (null != session.getAttribute("reportDataServerList") && bool) {
            List<BaseRepdatasource> dblist = (List<BaseRepdatasource>) session.getAttribute("reportDataServerList");
            for (BaseRepdatasource br : dblist) {
                for (String jurl : set) {
                    String filePath = jurl;//httpServletRequest.getSession().getServletContext().getRealPath(jurl);
                    File xmlFile = new File(filePath);
                    SAXReader saxx = new SAXReader();
                    Document documentedit;
                    try {
                        documentedit = saxx.read(xmlFile);
                        Element editroot = documentedit.getRootElement();
                        Element element = editroot.element("dataFile");
                        String url = element.element("url").getTextTrim();
                        String dbname = editroot.element("name").getTextTrim();
                        //判断是新上传的数据源文件需要重新加载
                        if (null != br.getRemark() && dbname.equals(br.getRemark())) {
                            int servertype = 0;
                            switch (br.getServicetype()) {
                                case "singleTableServer":
                                    servertype = 1;
                                    break;
                                case "executeSqlServer":
                                    servertype = 4;
                                    break;
                                case "masterConfigServer":
                                    servertype = 2;
                                    break;
                            }
                            List<BaseQueryfield> fieldList = baseQueryfieldService.getQueryFieldByServiceId(br.getDataserviceid(), servertype);
                            for (BaseQueryfield basefield : fieldList) {
                                BaseRepparmeter dbparmeter = new BaseRepparmeter();
                                dbparmeter.setGuid(UUID.randomUUID().toString());
                                dbparmeter.setServicecode(serviceId);
                                dbparmeter.setParmetername(basefield.getParametercode());
                                dbparmeter.setDatatype(basefield.getParamformat());
                                dbparmeter.setParmetertype("dataserverparmeter");
                                dbparmeter.setDataservercode(br.getDataserviceid());
                                dbparmeter.setDataservertype(br.getServicetype());
//								dbparmeter.setParmeterdesc(parmeterdesc);
                                dbparmeter.setIsterm("1");
                                list.add(dbparmeter);
                            }
                            //不是则去数据库查询
                        } else {
                            List<BaseRepparmeter> llist = baseRepparmeterService.getRdataParmBydataServiceId(serviceId, br.getDataserviceid());
                            for (BaseRepparmeter baseRepparmeter : llist) {
                                list.add(baseRepparmeter);
                            }
                        }
                    } catch (DocumentException e) {
                    }
                }
            }

        }
        session.setAttribute("dataServerParmeterList", list);
        List<BaseRepparmeter> getlist = new ArrayList<BaseRepparmeter>();
        for (BaseRepparmeter ob : list) {
            if (ob.getDataservercode().equals(dataserviceid)) {
                getlist.add(ob);
            }
        }
        jr.setData(getlist);
        jr.setSuccess(true);
        return jr;
    }

    /**
     * <pre>getDataSourceByServer(通过数据服务id获取数据源信息)
     * @author：FanWenquan
     * @date：2018年2月12日 下午4:53:14
     * @param serverId
     * @return</pre>
     */
    @RequestMapping("/getDataSourceByServer")
    @ResponseBody
    public Object getDataSourceByServer(String serverId) {
        BaseRepdatasource brd = null;
        HttpSession session = httpServletRequest.getSession();
        List<BaseRepdatasource> dblist = new ArrayList<BaseRepdatasource>();
        if (null != session.getAttribute("reportDataServerList")) {
            dblist = (List<BaseRepdatasource>) session.getAttribute("reportDataServerList");
            for (BaseRepdatasource baseRepdatasource : dblist) {
                if (baseRepdatasource.getDataserviceid().equals(serverId)) {
                    brd = baseRepdatasource;
                }
            }

        }
        return brd;
    }

    /**
     * <pre>insertCfgExtreportToSession(添加报表服务基本信息进入session)
     * @author：FanWenquan
     * @date：2018年2月9日 上午11:47:10
     * @param cfgExtreport
     * @return</pre>
     */
    @RequestMapping("/insertCfgExtreportToSession")
    @ResponseBody
    public Object insertCfgExtreportToSession(@RequestBody CfgExtreportExt cfgExtreport) {
        JsonResult jr = new JsonResult();
        try {
            HttpSession session = httpServletRequest.getSession();
            session.setAttribute("reportBaseInformation", cfgExtreport);
            jr.setSuccess(true);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            jr.setMsg("添加报表配置信息异常！");
            jr.setSuccess(false);
        }
        return jr;
    }
    //==============================报表服务保存配置===============================================

    /**
     * <pre>saveReportConfig(报表服务执行保存)
     * @author：FanWenquan
     * @date：2018年2月9日 下午1:10:56
     * @param operate
     * @return</pre>
     */
    @RequestMapping("saveReportConfig")
    @ResponseBody
    public Object saveReportConfig(String operate) {
        int size = 0;
        JsonResult jr = new JsonResult();
        try {
            if (null != operate && operate.equals("add")) {
                size += cfgExtreportService.insertReportAllConfig(httpServletRequest);
            } else if (null != operate && operate.equals("edit")) {
                size += cfgExtreportService.updateReportAllConfig(httpServletRequest);
            }
            jr.setSuccess(size > 0);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            jr.setSuccess(false);
        }
        return jr;
    }

    //==============================================================================================

    /**
     * <pre>updateDataServerParmeters(修改参数)
     * @author：FanWenquan
     * @date：2018年2月8日 上午11:39:57
     * @param baseRepparmeter
     * @return</pre>
     */
    @RequestMapping("/updateDataServerParmeters")
    @ResponseBody
    public Object updateDataServerParmeters(@RequestBody BaseRepparmeter baseRepparmeter) {
        int size = 0;
        HttpSession session = httpServletRequest.getSession();
        List<BaseRepparmeter> list = (List<BaseRepparmeter>) session.getAttribute("dataServerParmeterList");
        for (BaseRepparmeter br : list) {
            if (baseRepparmeter.getGuid().equals(br.getGuid())) {
                br.setAliasname(baseRepparmeter.getAliasname());
                br.setParmetervalue(baseRepparmeter.getParmetervalue());
                br.setOptionvalue(baseRepparmeter.getOptionvalue());
                br.setParmeterdesc(baseRepparmeter.getParmeterdesc());
                br.setIsterm(baseRepparmeter.getIsterm());
                size++;
                break;
            }
        }
        session.setAttribute("dataServerParmeterList", list);
        return size;

    }

    /**
     * <pre>updateRepparmeterSession(修改session中的属性配置)
     * @author：FanWenquan
     * @date：2018年2月7日 下午4:21:25
     * @param baseRepparmeter
     * @return</pre>
     */
    @RequestMapping("/updateRepparmeterSession")
    @ResponseBody
    public Object updateRepparmeterSession(@RequestBody BaseRepparmeter baseRepparmeter) {
        int size = 0;
        HttpSession session = httpServletRequest.getSession();
        List<BaseRepparmeter> list = (List<BaseRepparmeter>) session.getAttribute("reportParmeterList");
        for (BaseRepparmeter br : list) {
            if (baseRepparmeter.getGuid().equals(br.getGuid())) {
                br.setAliasname(baseRepparmeter.getAliasname());
                br.setParmetervalue(baseRepparmeter.getParmetervalue());
                br.setOptionvalue(baseRepparmeter.getOptionvalue());
                br.setParmeterdesc(baseRepparmeter.getParmeterdesc());
                br.setIsterm(baseRepparmeter.getIsterm());
                size++;
                break;
            }
        }
        session.setAttribute("reportParmeterList", list);
        return size;
    }

    /**
     * <pre>insertCfgExtreport(添加报表配置信息)
     * @author：FanWenquan
     * @date：2018年1月5日 下午4:50:47
     * @param cfgExtreport
     * @return</pre>
     */
    @RequestMapping("/insertCfgExtreport")
    @ResponseBody
    public Object insertCfgExtreport(@RequestBody CfgExtreportExt cfgExtreport) {
        JsonResult jr = new JsonResult();
        try {
            cfgExtreportService.insertCfgExtreport(cfgExtreport);
            jr.setSuccess(true);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            jr.setMsg("添加报表配置信息异常！");
            jr.setSuccess(false);
        }
        return jr;
    }

    /**
     * <pre>deleteCfgExtreport(删除报表服务配置信息)
     * @author：FanWenquan
     * @date：2018年1月5日 下午4:56:16
     * @param guid
     * @return</pre>
     */
    @RequestMapping("/deleteCfgExtreport")
    @ResponseBody
    public Object deleteCfgExtreport(String guid) {
        JsonResult jr = new JsonResult();
        try {
            cfgExtreportService.deleteCfgExtreport(guid);
            jr.setSuccess(true);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            jr.setMsg("删除报表配置信息异常！");
            jr.setSuccess(false);
        }
        return jr;
    }

    /**
     * <pre>updateCfgExtreport(修改报表服务配置信息)
     * @author：FanWenquan
     * @date：2018年1月5日 下午4:56:44
     * @param cfgExtreport
     * @return</pre>
     */
    @RequestMapping("/updateCfgExtreport")
    @ResponseBody
    public Object updateCfgExtreport(@RequestBody CfgExtreport cfgExtreport) {
        JsonResult jr = new JsonResult();
        try {
            cfgExtreportService.updateCfgExtreport(cfgExtreport);
            jr.setSuccess(true);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            jr.setMsg("修改报表配置信息异常！");
            jr.setSuccess(false);
        }
        return jr;
    }

    /**
     * <pre>valReportServerCode(校验报表服务编码)
     * @author：FanWenquan
     * @date：2018年1月6日 上午11:15:59
     * @param guid
     * @return</pre>
     */
    @RequestMapping("/valReportServerCode")
    @ResponseBody
    public Object valReportServerCode(String guid) {
        JsonResult jr = new JsonResult();
        try {
            CfgExtreport cfgExtreport = cfgExtreportService.getReportConfigByGuid(guid);
            if (null != cfgExtreport) {
                jr.setSuccess(false);
            } else {
                jr.setSuccess(true);
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            jr.setMsg("获取报表服务异常！");
            jr.setSuccess(false);
        }
        return jr;
    }

    /**
     * <pre>valJrxmlJasper(校验报表模板文件是否存在)
     * @author：FanWenquan
     * @date：2018年2月8日 下午6:04:07
     * @param guid
     * @return</pre>
     */
    @RequestMapping("/valJrxmlJasper")
    @ResponseBody
    public Object valJrxmlJasper(String guid) {
        Boolean bol = false;
        HttpSession session = httpServletRequest.getSession();
        BaseReptemplate temp = baseReptempletService.getReptemplateByServiceid(guid);
        Boolean valtemp = null != temp;
        Boolean valsession = null != session.getAttribute("reportJrxmlUrl") && null != session.getAttribute("reportJasperUrl");
        if (valtemp || valsession) {
            bol = true;
        }
        return bol;
    }

    /**
     * <pre>valDateSourceExist(校验数据源是否存在)
     * @author：FanWenquan
     * @date：2018年2月9日 上午9:38:27
     * @param guid
     * @return</pre>
     */
    @RequestMapping("/valDateSourceExist")
    @ResponseBody
    public Object valDateSourceExist(String operate, String serviceId) {
        Boolean getdataServerConfig = getdataServerConfig(operate, serviceId);
        Boolean bol = true;
        HttpSession session = httpServletRequest.getSession();
        List<BaseRepdatasource> list = null;
        if (getdataServerConfig) {
            list = (List<BaseRepdatasource>) session.getAttribute("reportDataServerList");
        }
        for (BaseRepdatasource baseRepdatasource : list) {
            if (null == baseRepdatasource.getDataserviceid()) {
                bol = false;
                break;
            }
        }
//		List<BaseRepdatasource> dbsize = baseRepdatasourceService.getReportDataSourceByServer(serviceId);
//		Boolean valdb = null != dbsize && dbsize.size()>0;
//		Boolean valsession= null!=session.getAttribute("dataJsonXml");1
//		if(valdb || valsession) {
//			bol = true;
//		}
        return bol;
    }

    /**
     * <pre>valAliasnameExist(校验数据源参数别名是否唯一)
     * @author：FanWenquan
     * @date：2018年2月9日 上午11:03:04
     * @param guid
     * @param aliasname
     * @return</pre>
     */
    @RequestMapping("/valReportAliasnameExist")
    @ResponseBody
    public Object valReportAliasnameExist(String guid, String aliasname) {
        Boolean bol = true;
        HttpSession session = httpServletRequest.getSession();
        List<BaseRepparmeter> list = (List<BaseRepparmeter>) session.getAttribute("reportParmeterList");
        if (null != list) {
            for (BaseRepparmeter baseRepparmeter : list) {
                if (!guid.equals(baseRepparmeter.getGuid())) {
                    if (null != aliasname && !"".equals(aliasname) && aliasname.equals(baseRepparmeter.getAliasname())) {
                        bol = false;
                    }
                }
            }
        }
        List<BaseRepparmeter> dlist = (List<BaseRepparmeter>) session.getAttribute("dataServerParmeterList");
        if (null != dlist) {
            for (BaseRepparmeter baseRepparmeter : dlist) {
                if (!guid.equals(baseRepparmeter.getGuid())) {
                    if (null != aliasname && !"".equals(aliasname) && aliasname.equals(baseRepparmeter.getAliasname())) {
                        bol = false;
                    }
                }
            }
        }
        return bol;
    }

    /**
     * <pre>valDBAliasnameExist(校验数据服务参数是否唯一)
     * @author：FanWenquan
     * @date：2018年2月9日 上午11:19:07
     * @param guid
     * @param aliasname
     * @return</pre>
     */
    @RequestMapping("/valDBAliasnameExist")
    @ResponseBody
    public Object valDBAliasnameExist(String guid, String aliasname) {
        Boolean bol = true;
        HttpSession session = httpServletRequest.getSession();
        List<BaseRepparmeter> list = (List<BaseRepparmeter>) session.getAttribute("dataServerParmeterList");
        if (null != list) {
            for (BaseRepparmeter baseRepparmeter : list) {
                if (!guid.equals(baseRepparmeter.getGuid())) {
                    if (null != aliasname && !"".equals(aliasname) && aliasname.equals(baseRepparmeter.getAliasname())) {
                        bol = false;
                    }
                }
            }
        }
        List<BaseRepparmeter> rlist = (List<BaseRepparmeter>) session.getAttribute("reportParmeterList");
        if (null != rlist) {
            for (BaseRepparmeter baseRepparmeter : rlist) {
                if (!guid.equals(baseRepparmeter.getGuid())) {
                    if (null != aliasname && !"".equals(aliasname) && aliasname.equals(baseRepparmeter.getAliasname())) {
                        bol = false;
                    }
                }
            }
        }
        return bol;
    }
    /**
     * <pre>getReportParmeter(获取报表参数并添加到数据库)
     * @author：FanWenquan
     * @date：2018年1月6日 下午1:02:50
     * @param serviceId
     * @param request
     * @return</pre>
     */
//	@RequestMapping("/getReportParmeter")
//	@ResponseBody
//	public Object getReportParmeter(String serviceId, HttpServletRequest request) {
//		JsonResult jr = new JsonResult();
//		try {
//			List<BaseRepparmeter> list = new ArrayList<BaseRepparmeter>();
//			BaseReptemplate reptemplate = baseReptempletService.getReptemplateByServiceid(serviceId);
//			//获取模板文件目录位置
//			String filePath = request.getSession().getServletContext().getRealPath(reptemplate.getJrxmlUrl());
//			File xmlFile=new File(filePath);
//        	SAXReader sax=new SAXReader();
//        	Document document=sax.read(xmlFile);
//        	Element root=document.getRootElement();
//        	List<Element> parmeterlist = root.elements("parameter");
//            for (Element element : parmeterlist) {
//            	String classvalue = element.attributeValue("class");
//            	int lastindexof = classvalue.lastIndexOf(".");
//            	String type=classvalue.substring(lastindexof+1);
//            	if(null != type && !type.equals("JRBeanCollectionDataSource")) {
//            		BaseRepparmeter repparmeter = new BaseRepparmeter();
//                	repparmeter.setGuid(UUID.randomUUID().toString());
//                	repparmeter.setParmetername(element.attributeValue("name"));
//                	repparmeter.setParmetertype(type);
//                	repparmeter.setParmeterdesc(element.elementText("parameterDescription"));
//                	repparmeter.setServicecode(serviceId);
//                	list.add(repparmeter);
//            	}
//			}
//            Integer size = baseRepparmeterService.insertRepparmeterConfig(list);
//    		jr.setData(list);
//    		jr.setSuccess(true);
//		} catch (Exception e) {
//			logger.error(e.getMessage(), e);
//			jr.setMsg("获取报表参数异常！");
//			jr.setSuccess(false);
//		}
//		return jr;
//	}

    /**
     * <pre>getReportDateSource(从模板文件获取数据源信息)
     * @author：FanWenquan
     * @date：2018年1月6日 下午1:58:52
     * @param serviceId
     * @param request
     * @return</pre>
     */
//	@RequestMapping("/getReportDateSource")
//	@ResponseBody
//	public Object getReportDateSource(String serviceId, HttpServletRequest request) {
//		JsonResult jr = new JsonResult();
//		try {
//			List<BaseRepdatasource> list = new ArrayList<BaseRepdatasource>();
//			BaseReptemplate reptemplate = baseReptempletService.getReptemplateByServiceid(serviceId);
//			//获取模板文件目录位置
//			String filePath = request.getSession().getServletContext().getRealPath(reptemplate.getJrxmlUrl());
//			File xmlFile=new File(filePath);
//        	SAXReader sax=new SAXReader();
//        	Document document=sax.read(xmlFile);
//        	Element root=document.getRootElement();
//        	List<Element> parmeterlist = root.elements("parameter");
//            for (Element element : parmeterlist) {
//            	String classvalue = element.attributeValue("class");
//            	int lastindexof = classvalue.lastIndexOf(".");
//            	String type=classvalue.substring(lastindexof+1);
//            	if(null != type && type.equals("JRBeanCollectionDataSource")) {
//            		BaseRepdatasource datasource = new BaseRepdatasource();
//                	datasource.setGuid(UUID.randomUUID().toString());
//                	datasource.setServicecode(serviceId);
//                	datasource.setRepdatasource(element.attributeValue("name"));
//                	datasource.setDatesourcedesc(element.elementText("parameterDescription"));
//                	datasource.setIsdefault(1L);
//                	list.add(datasource);
//            	}
//			}
//            BaseRepdatasource defaultds = new BaseRepdatasource();
//            defaultds.setGuid(UUID.randomUUID().toString());
//            defaultds.setServicecode(serviceId);
//            defaultds.setRepdatasource("DefaultDataSource");
//            defaultds.setDatesourcedesc("默认数据源");
//            defaultds.setIsdefault(0L);
//            list.add(defaultds);
//            int size = baseRepdatasourceService.insertBaseRepdatasource(list);
//    		jr.setSuccess(true);
//		} catch (Exception e) {
//			logger.error(e.getMessage(), e);
//			jr.setMsg("获取报表数据源异常！");
//			jr.setSuccess(false);
//		}
//		return jr;
//	}

    /**
     * <pre>getReportParmByServer(根据服务获取参数配置)
     * @author：FanWenquan
     * @date：2018年1月6日 下午2:50:11
     * @return</pre>
     */
    @RequestMapping("/getReportParmByServer")
    @ResponseBody
    public Object getReportParmByServer(String serviceId) {
        JsonResult jr = new JsonResult();
        try {
            List<BaseRepparmeter> list = baseRepparmeterService.getReportParmByServer(serviceId);
            jr.setSuccess(true);
            jr.setData(list);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            jr.setMsg("获取参数配置异常！");
            jr.setSuccess(false);
        }
        return jr;
    }

    @RequestMapping("/updateRepparmeter")
    @ResponseBody
    public Object updateRepparmeter(@RequestBody BaseRepparmeter baseRepparmeter) {
        Integer size = baseRepparmeterService.updateRepparmeter(baseRepparmeter);
        return size;
    }

    /**
     * <pre>getReportDataSourceByServer(根据服务获取数据源配置)
     * @author：FanWenquan
     * @date：2018年1月6日 下午2:55:05
     * @param serviceId
     * @return</pre>
     */
    @RequestMapping("/getReportDataSourceByServer")
    @ResponseBody
    public Object getReportDataSourceByServer(String serviceId) {
        JsonResult jr = new JsonResult();
        try {
            List<BaseRepdatasource> list = baseRepdatasourceService.getReportDataSourceByServer(serviceId);
            jr.setSuccess(true);
            jr.setData(list);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            jr.setMsg("获取数据源配置异常！");
            jr.setSuccess(false);
        }
        return jr;
    }

    /**
     * <pre>updateReportDataSource(修改数据源配置)
     * @author：FanWenquan
     * @date：2018年1月6日 下午5:50:42
     * @param list
     * @return</pre>
     */
    @RequestMapping("/updateReportDataSource")
    @ResponseBody
    public Object updateReportDataSource(@RequestBody List<BaseRepdatasource> list) {
        JsonResult jr = new JsonResult();
        try {
            int size = baseRepdatasourceService.updateReportDataSource(list);
            jr.setSuccess(true);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            jr.setMsg("修改数据源配置异常！");
            jr.setSuccess(false);
        }
        return jr;
    }

    @RequestMapping("/clearSession")
    @ResponseBody
    public Object clearSession() {
        HttpSession session = httpServletRequest.getSession();
        session.removeAttribute("reportJasperUrl");//jasper文件地址缓存
        session.removeAttribute("reportJrxmlUrl");//jrxml文件地址缓存
        session.removeAttribute("dataJsonXml");//数据源json文件地址缓存
        session.removeAttribute("reportDataServerList");//报表数据源服务缓存
        session.removeAttribute("reportserverID");//报表服务id缓存
        session.removeAttribute("reportParmeterList");//报表属性参数缓存
        session.removeAttribute("dataServerParmeterList");//报表数据源参数缓存
        session.removeAttribute("reportBaseInformation");//报表基本配置缓存
        session.removeAttribute("dataSourceInfoTemp");//清除零时数据源报表信息
//		String uploadRootPath = httpServletRequest.getSession().getServletContext().getRealPath("/WEB-INF/jasper/jsondata");
//		FileControlUtil.deleteDir(new File(uploadRootPath));
        return null;
    }

}
